package com.ywyself.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.ywyself.ext.kit.JoinSql;
import com.ywyself.ext.kit.YsKit;
import com.ywyself.ext.utils.YsDateUtils;
import com.ywyself.model.Diary;

/**
 * 言语记录
 * 
 * @author YuWenYue
 * @date 2017年11月6日 下午7:01:35
 */
public class DiaryDao {
    private static final String TABLE_NAME = "ys_diary";

    /**
     * 增加
     * 
     * @param diary
     * @return
     */
    public YsKit save(Diary diary) {
        try {
            Date d = new Date();
            diary.setAddTime(d);
            diary.setUpdateTime(d);
            if (diary.save()) {
                return YsKit.ok().code("100").msg("保存成功");
            } else {
                return YsKit.fail().code("400").msg("保存失败");
            }
        } catch (Exception e) {
            LogKit.error("DiaryDao.save():" + e.getLocalizedMessage());
            return YsKit.sqlError().code("410");
        }
    }

    /**
     * 删除
     * 
     * @param id
     * @return
     */
    public boolean delete(long id) {
        return Diary.dao.deleteById(id);
    }

    /**
     * 更新
     * 
     * @param id
     * @param content
     * @param author
     * @param remark
     * @return
     */
    public YsKit update(long id, String content, String author, String remark) {
        Map<String, Object> data = new HashMap<String, Object>(4);
        data.put("content", content);
        data.put("author", author);
        data.put("remark", remark);
        return updateColumnsById(id, data);
    }

    /**
     * 更新
     * 
     * @param cid
     *            分类id
     * @param data
     *            待修改的内容
     * @return
     */
    private YsKit updateColumnsById(long id, Map<String, Object> data) {
        try {
            data.put("update_time", YsDateUtils.getStr());
            String sql = JoinSql.joinUpdate(id, TABLE_NAME, data);
            int num = Db.update(sql);
            if (num > 0) {
                return YsKit.ok().msg("更新成功").code("101");
            } else {
                return YsKit.fail().msg("更新失败").code("400");
            }
        } catch (Exception e) {
            LogKit.error("DiaryDao.updateColumnsById():" + e.getLocalizedMessage());
            return YsKit.sqlError().code("410");
        }
    }

    /**
     * 基于id查询数据
     * 
     * @param id
     * @return
     */
    public Diary get(long id) {
        return Diary.dao.findById(id);
    }

    /**
     * 查询
     * 
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public Page<Record> page(int pageNumber, int pageSize) {
        Map<String, String> select = new HashMap<String, String>();
        select.put("id", null);
        select.put("content", null);
        select.put("author", null);
        select.put("remark", null);
        select.put("update_time", null);
        return pageByCond(pageNumber, pageSize, select, null);
    }

    /**
     * 多条件查询数据
     * 
     * @param pageNumber
     * @param pageSize
     * @param select
     *            为null则查询所有， 查询的参数，字段=别名，别名可以为null
     * @param cond
     *            为空则表示无条件， 条件，条件=值,多条件之间只有and连接
     * @return
     */
    private Page<Record> pageByCond(int pageNumber, int pageSize, Map<String, String> select,
            Map<String, Object> cond) {
        try {
            String update_time = "update_time";
            StringBuffer sel = new StringBuffer("SELECT ");
            if (select == null || select.size() == 0) {
                sel.append("*");
            } else {
                update_time = select.get("update_time") == null ? "update_time" : select.get("update_time");
                boolean isFirstSel = true;
                for (Entry<String, String> entry : select.entrySet()) {
                    if (isFirstSel) {
                        isFirstSel = false;
                        sel.append("");
                    } else {
                        sel.append(", ");
                    }
                    sel.append(entry.getKey());
                    if (entry.getValue() != null && entry.getValue().trim() != "") {
                        sel.append(" AS ").append(entry.getValue());
                    }
                }
            }
            StringBuffer wh = new StringBuffer();
            wh.append(" FROM ").append(TABLE_NAME);
            boolean isFirstCond = true;
            if (cond != null && cond.size() > 0) {
                for (Entry<String, Object> d : cond.entrySet()) {
                    if (isFirstCond) {
                        isFirstCond = false;
                        wh.append(" WHERE ");
                    } else {
                        wh.append(" AND ");
                    }
                    wh.append(d.getKey()).append(" = '").append(d.getKey());
                }
            }
            wh.append(" ORDER BY " + update_time + " DESC");
            return Db.paginate(pageNumber, pageSize, sel.toString(), wh.toString());
        } catch (Exception e) {
            LogKit.error("CatelogDao.pageByCond():" + e.getLocalizedMessage());
            return new Page<Record>();
        }
    }
}
